<template>
  <div class="body_">
    <!-- <div class="header">
      <div class="TitleForm">
        <el-form
          ref="SearchForm"
          :model="SearchForm"
          label-width="120px"
          inline
        >
          <el-form-item prop="name" label="歌曲名称">
            <el-input
              placeholder="请输入名称或编码"
              v-model="SearchForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item prop="state" label="设备状态">
            <el-input
              placeholder="选择设备状态"
              v-model="SearchForm.state"
            ></el-input>
          </el-form-item>

                   <el-form-item prop="name" label="设备编码">
                    <el-input
                       placeholder="请输入名称或编码"
                      v-model="SearchForm.name"
                      ></el-input>
                  </el-form-item>
        </el-form>
        <div class="queryBtn">
          <el-button @click="Select(true)" type="primary" icon="el-icon-search"
            >搜索</el-button
          >
          <el-button
            @click="resetSearchForm('SearchForm')"
            type="primary"
            icon="el-icon-refresh-left"
            >重置</el-button
          >
        </div>
      </div>
    </div> -->

    <div class="main">
      <div class="tableBtn">
        <el-button type="primary" icon="el-icon-plus" @click="SelectMusic()">新增</el-button>
      </div>
      <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        :data="tableData" style="width: 100%">
        <el-table-column prop="id" type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="180">
        </el-table-column>
        <el-table-column prop="list" label="歌曲" width="380">
        </el-table-column>
        <el-table-column prop="latLng" label="操作">
          <template slot-scope="scope">
            <!--  <span class="operter">编辑</span> -->
            <span class="operter" @click="delPlayList(scope.row)">删除 </span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="block" style="margin-top: 15px">
        <el-pagination align="center" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage" :page-sizes="[1, 5, 10]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="DialogTitle" :visible.sync="AddDialogFormVisible" center width="30%" @close="CloseAddDialog">
      <el-form ref="AddForm">
        <el-form-item class="ipt_item" label="列表名称" label-width="120px" prop="name">
          <el-input v-model="name" class="ipt_item_Input" style="width: 330px;"></el-input>
        </el-form-item>
        <el-form-item class="ipt_item" label="音乐列表" label-width="120px" prop="name">
          <el-select size="medium" multiple filterable :disabled="disabled" v-model="selectedArr"
            :loading="mulSelectLoading" :collapse-tags="collapseTags" placeholder="请选择" @remove-tag="removeTag"
            style="width: 330px;">
            <el-option label="全部" value="全部" @click.native="selectAll" v-if="selectOptions.length"></el-option>
            <el-option v-for="item in selectOptions" :key="item.value" :label="item.key" :value="item.value"
              @click.native="changeSelect"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="AddDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

  </div>
</template>

<script>
  import _ from 'lodash'
  import {
    IPPBXLogin,
    getPlayList,
    getMusicList,
    addToPlay,
    delPlayList,
  } from "@/api/Audio";
  export default {
    name: 'MultipleSelect',
    watch: {
      mulSelecteds: {
        handler(newVal, oldVal) {
          this.selectedArr = newVal
          if (
            !this.selectedArr.includes('全部') &&
            this.selectedArr.length &&
            this.selectedArr.length === this.selectOptions.length
          ) {
            this.selectedArr.unshift('全部')
          }
          if (this.selectedArr.includes('全部')) this.selectAll()
        },
        immediate: true,
      },
    },
    props: {
      // 选项
      selectOptions: {
        type: Array,
        default () {
          return []
        },
      },
      // 是否禁用
      disabled: {
        type: Boolean,
        default: false,
      },
      // 已选中选项
      mulSelecteds: {
        type: Array,
        default () {
          return []
        },
      },
      mulSelectLoading: {
        type: Boolean,
        default: false,
      },
      collapseTags: {
        type: Boolean,
        default: true,
      },
      compIndex: {
        type: [String, Number],
        default: null,
      },
    },
    mounted() {
      this.login();
    },
    data() {
      return {
        selectedArr: [],
        selectedIds: [],
        tableData: [],
        musicList: [],
        authorization:"",
        currentPage: 1, // 当前页码
        total: 20, // 总条数
        pageSize: 10, // 每页的数据条数
        // 新增弹窗
        AddDialogFormVisible: false,
        DialogTitle: "新增播放列表",
        name: ""
      };
    },
    methods: {
      // 登录
      async login() {
        let data = await IPPBXLogin();
        console.log(data);
        this.authorization=data.data;
        if(data.code==0){
           this. Select();
        }
      },
      selectAll() {
        const selectedArrLen = this.selectedArr.length
        const selectOptionsLen = this.selectOptions.length
        // 未全选(注意只有一个的条件判断)
        if (
          selectedArrLen < selectOptionsLen ||
          (selectedArrLen === 1 && selectedArrLen === selectOptionsLen)
        ) {
          this.selectedArr = this.selectOptions.map((el) => el.value)
          this.selectedArr.unshift('全部')
        } else {
          // 已全选时，点击则取消全部
          this.selectedArr = []
        }
        this.emitChangeSelect()
      },
      changeSelect() {
        if (this.selectedArr.includes('全部')) this.selectedArr.shift('全部')
        if (this.selectedArr.length == this.selectOptions.length)
          this.selectedArr.unshift('全部')
        this.emitChangeSelect()
      },
      removeTag(val) {
        if (val === '全部') {
          this.selectedArr = []
        }
        this.emitChangeSelect()
      },
      emitChangeSelect() {
        const selectedList = _.cloneDeep(this.selectedArr)
        if (selectedList.includes('全部')) selectedList.shift('全部')
        this.$emit('changeSelect', selectedList, this.compIndex)
        console.log(this.selectedArr);
        console.log(this.selectOptions);
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      handleSizeChange(e) {
        this.pageSize = e;
        this.Select(false);
      },
      handleCurrentChange(e) {
        this.currentPage = e;
        this.Select(false);
      },
      // 查询
      async Select(type) {
        if (type) {
          this.currentPage = 1;
        }
        let {
          data: res
        } = await getPlayList({
          page: this.currentPage,
          pageSize: this.pageSize,
          authorization: this.authorization,
        });
        console.log(res);
        this.tableData = [];
        this.total = Number(res.count);
        res.items.forEach((e) => {
          let item = {
            id: e.id,
            name: e.name,
          };
          let m=[];
          e.musics.forEach((c)=>{
            m.push(c.showName);
          });
          item.list= m.join(",");
          this.tableData.push(item);
        });
      },
      CloseAddDialog() {
        this.$refs["AddForm"].resetFields();
        this.DialogTitle = "创建播放列表";
        this.isAdd = true;
        this.EditQuery = {};
      },
      async SelectMusic() {
        let {
          data: res
        } = await getMusicList({
          page: 1,
          authorization:this.authorization,
          pageSize: this.pageSize,
        });
        console.log(res);
        this.musicList = [];
        this.musicList = res.items;
        res.items.forEach((e) => {
          let item = {
            key: e.showName,
            value: e.id
          };
          this.selectOptions.push(item);
        });
        this.AddDialogFormVisible = true;
      },
      // 删除该播放列表
      delPlayList(row) {
        this.$confirm("此操作将永久删除该播放列表, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            console.log(row);
            delPlayList({
              authorization: this.authorization,
              ids: "[" + row.id + "]"
            }).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.Select(true);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      //添加播放列表
      submit() {
        if (this.name = "") {
          this.$message({
            type: "info",
            message: "请输入播放列表名称",
          });
        }
        if (this.selectedArr.length == 0) {
          this.$message({
            type: "info",
            message: "请选择播放列表的音乐",
          });
        }
        if (this.selectedArr.includes('全部')) this.selectedArr.shift('全部')
        this.selectedArr.forEach((e) => {
          console.log(e);
          console.log(this.musicList);
          this.selectedIds.push(this.musicList[e].id);
        });
        addToPlay({
          name: this.name,
          authorization: this.authorization,
          musicIds: "[" + this.selectedIds.join(",") + "]"
        }).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.Select(true);
            this.AddDialogFormVisible = false;
          }
        });
      }

    },
  };
</script>

<style lang="scss" scoped>
  .body_ {
    overflow: hidden;
    padding-top: 0.2625rem;
    padding-left: 10px;
    padding-right: 10px;
    padding-bottom: 5px;
    display: flex;
    flex-direction: column;

    //height: 820px;
    .header {
      width: 100%;
      //height: 0.85rem /* 68/80 */;
      border-radius: 4px;
      background-color: rgb(255, 255, 255);
      box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    }

    .main {
      margin-top: 0.3rem
        /* 24/80 */
      ;
      width: 100%;
      //height: 8.925rem /* 618/80 */;
      border-radius: 4px;
      background-color: rgb(255, 255, 255);
      box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
      flex: 1;
    }
  }

  .operter {
    color: rgba(59, 140, 255, 1) !important;
    cursor: pointer;
    margin-right: 4px;
  }
</style>
